package com.geek.demo01.exception;

import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @ClassName GlobalException
 * @Description TODO
 * @Author zzm
 * @Data 2020/10/20 19:23
 * @Version 1.0
 */
@RestControllerAdvice
public class GlobalException {

    /**
     * 未知异常捕获
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public UnifyResponse handleException(HttpServletRequest req, Exception e) {
        String url = req.getRequestURI();
        String method = req.getMethod();
        UnifyResponse message = new UnifyResponse(9999, "服务器异常", method + " " + url);
        return message;
    }

    @ExceptionHandler(value = ServiceException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public UnifyResponse handleException(HttpServletRequest req, ServiceException e) {
        String url = req.getRequestURI();
        String method = req.getMethod();
        UnifyResponse message = new UnifyResponse(e.getCode(), e.getMessage(), method + " " + url);
        return message;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public UnifyResponse handleMethodException(HttpServletRequest req, MethodArgumentNotValidException exception) {
        List<ObjectError> errorList = exception.getBindingResult().getAllErrors();
        ObjectError err = errorList.stream().findFirst().get();
        String msg = err.getDefaultMessage();

        String url = req.getRequestURI();
        String method = req.getMethod();

        return new UnifyResponse(50000, msg, method + " " + url);
    }

}
